// var role = require("./role");
var http = require("http");
var request = require("request");
var htmlparser = require("htmlparser2");
var ResponObj = require("../_include/responObj");
var When = require("../_include/common").When;
var gbk = require("gbk");
var minyun_fishing_core = {
	cache: {},
	get_img_code: function(id, options) {
		var minyun_login_img_url = "http://pw.minyun.com.cn:8008/ticket-web/security/jcaptcha.jpg";
		http.get(minyun_login_img_url, function(res) {
			var buffers = [];
			minyun_fishing_core.cache[id] = res.headers["set-cookie"];
			res.on("data", function(chunk) {
				buffers.push(chunk);
				options.ondata && options.ondata(chunk)
			});
			res.on("end", function() {
				options.onend && options.onend(buffers)
			});
		});
	},
	login: function(id, options) {
		var minyun_login_url = "http://pw.minyun.com.cn:8008/ticket-web/user/v_minyun_login.jhtml";
		var _success_loc_url = "http://pw.minyun.com.cn:8008/ticket-web/user/index.jhtml";
		var _error_loc_url = "http://pw.minyun.com.cn:8008/ticket-web/login.jhtml?error=";
		var j = request.jar();
		j.setCookie(minyun_fishing_core.cache[id].toString(), "http://pw.minyun.com.cn:8008");
		request.post(minyun_login_url, {
			form: {
				loginName: options.username,
				password: options.password,
				j_captcha: options.captcha
			},
			jar: j
		}, function(error, response, body) {
			var location = response.headers["location"];
			if (location) {
				if (location == _success_loc_url) {
					options.onsuccess && options.onsuccess()
				} else if (location.indexOf(_error_loc_url) !== -1) {
					var error_msg_map = {
						"2": "验证码有误"
					};
					var error_code = location.replace(_error_loc_url, "");
					options.onerror && options.onerror(error_msg_map[error_code] || error_code);
				} else {
					options.onerror && options.onerror("未知错误");
				}
			} else {
				options.onerror && options.onerror("用户名或者密码错误");
			}
		})
	},
	get_user_info: function(id, options) {
		var minyun_userinfo_url = "http://pw.minyun.com.cn:8008/ticket-web/user/myInfo.jhtml";
		var j = request.jar();
		j.setCookie(minyun_fishing_core.cache[id].toString(), "http://pw.minyun.com.cn:8008");
		request.get(minyun_userinfo_url, {
			jar: j
		}, function(error, response, body) {

			var user_info = {};
			var parser = new htmlparser.Parser({
				onopentag: function(name, attribs) {
					if (name === "input" && attribs.type === "text") {
						user_info[attribs.name] = attribs.value
					}
				}
			}, {
				decodeEntities: true
			});
			parser.write(body);
			parser.end();
			options.onsuccess && options.onsuccess(user_info)
		});
	},
};
var mju_fishing_core = {
	cache: {},
	get_img_code: function(id, options) {
		var session = mju_fishing_core.cache[id] = {};
		var mju_login_url = "http://jwgl.mju.edu.cn/default2.aspx";
		var w = When(2);
		//获取登录也定时改变的__VIEWSTATE
		request.get(mju_login_url, function(err, res, body) {
			// console.log(body)
			//虽然是GBK编码，但是viewstate是base64字符串，所以无所谓
			var parser = new htmlparser.Parser({
				onopentag: function(name, attribs) {
					if (name === "input" && attribs.name === "__VIEWSTATE") {
						w.ok(0);
						session.viewstate = attribs.value;
					}
				}
			}, {
				decodeEntities: true
			});
			parser.write(body);
			parser.end();
		});
		var minyun_login_img_url = "http://jwgl.mju.edu.cn/CheckCode.aspx";
		http.get(minyun_login_img_url, function(res) {
			var buffers = [];
			session.cookies = res.headers["set-cookie"];

			res.on("data", function(chunk) {
				buffers.push(chunk);
				options.ondata && options.ondata(chunk)
			});
			res.on("end", function() {
				w.ok(1);
				w.then(function() {
					options.onend && options.onend(buffers)
				});
			});
		});
	},
	login: function(id, options) {
		var mju_login_url = "http://jwgl.mju.edu.cn/default2.aspx";
		var _success_loc_url = "/xs_main.aspx?xh=" + options.username;
		var j = request.jar();
		var session = mju_fishing_core.cache[id] || {};
		j.setCookie(session.cookies.toString(), "http://jwgl.mju.edu.cn");
		session.username = options.username;
		session.password = options.password;

		var gbk_buffers = [];
		request.post(mju_login_url, {
			form: {
				__VIEWSTATE: session.viewstate,
				txtUserName: options.username,
				TextBox2: options.password,
				txtSecretCode: options.captcha,
				RadioButtonList1: encodeURIComponent(gbk.toBuffer('utf-8', "学生")) /*"%D1%A7%C9%FA" */ /*encodeURIComponent('学生')*/ ,
				Button1: "",
				lbLanguage: "",
				hidPdrs: "",
				hidsc: "",
			},
			jar: j
		}, function(error, response, body) {
			console.log(response.headers)
			var location = response.headers["location"];
			if (location) {
				if (location == _success_loc_url) {
					options.onsuccess && options.onsuccess()
				} else {
					console.log("location:", location)
					options.onerror && options.onerror("未知错误");
				}
			} else {
				gbk_buffers = Buffer.concat(gbk_buffers);
				var utf8String = gbk.toString('utf-8', gbk_buffers);
				// console.log(body)
				var err = utf8String.match(/alert\(\'(.+?)\'\)/) || []
				options.onerror && options.onerror(err[1] || "未知错误");
			}
		}).on("data", function(chunk) {
			gbk_buffers.push(chunk);
		})
	},
	_parse_user_info: function(body) {
		var user_info = {};

		var _current_cache_key = null;
		var _INTO_GET_KEY;
		var _INTO_GET_VALUE;
		var _cahce = {
			key: null,
			value: null
		};
		var parser = new htmlparser.Parser({
			onopentag: function(name, attribs) {
				// console.log("open:", name, attribs);
				switch (name) {
					case "td":
						if (!_cahce.key) { //取key
							if (attribs.class === "trbg1") {
								_INTO_GET_KEY = true;
							}
						} else { //已经取到key了，下一个td就是取value
							_INTO_GET_VALUE = true
						}
						break;
					case "span":
						if (_INTO_GET_KEY) { //td.trbg1>span是key的内容
							_current_cache_key = "key"; //开始key
						}
						if (_INTO_GET_VALUE) { //开始取value
							_current_cache_key = "value";
						}
						break;
					case "input":
						if (_current_cache_key === "value") { //value在input中
							_cahce[_current_cache_key] = attribs.value;
						}
						break;
					case "option":
						if (_current_cache_key === "value" && attribs.selected === "selected") { //value在input中
							_cahce[_current_cache_key] = attribs.value
						}
						break;
				}

				// if (name === "img" && attribs.id === "xszp") {
				//学生照片
				// }
			},
			ontext: function(text) {
				// console.log("text:", text);
				if (_current_cache_key) {
					_cahce[_current_cache_key] = text;
					_current_cache_key = null;
				}
			},
			onclosetag: function(tagname) {
				// console.log("close:", tagname);
				switch (tagname) {
					case "td":
						// console.log(_INTO_GET_KEY, _INTO_GET_VALUE)
						if (_INTO_GET_KEY) {
							_INTO_GET_KEY = false; //关闭取key
						}
						if (_INTO_GET_VALUE) {
							_INTO_GET_VALUE = false; //关闭取value
							// 将key-value写入user-info
							// console.log(`<<<<<<<<<<<<<<<<${_cahce.key}|${_cahce.key}>>>>>>>>>>>>>>>>>>>`)
							if (_cahce.key && _cahce.value && (_cahce.value = _cahce.value.trim())) {
								user_info[_cahce.key.replace("：", "")] = _cahce.value
							}
							//删除缓存，准备下一轮的取值
							_cahce.key = null;
							_cahce.value = null;
						}
						break;
					case "span":
						if (_current_cache_key) {
							_current_cache_key = null; //结束取值
						}
						break;
				}
			}
		}, {
			decodeEntities: true
		});
		parser.write(body);
		parser.end();

		return user_info;
	},
	get_user_info: function(id, options) {
		var session = mju_fishing_core.cache[id];
		var mju_userinfo_url = "http://jwgl.mju.edu.cn/xsgrxx.aspx?xh=" + session.username;
		var gbk_buffers = [];
		var j = request.jar();
		j.setCookie(session.cookies.toString(), "http://jwgl.mju.edu.cn");
		request.get(mju_userinfo_url, {
			jar: j
		}, function(error, response, body) {
			gbk_buffers = Buffer.concat(gbk_buffers);
			var utf8_body = gbk.toString('utf-8', gbk_buffers);

			var user_info = mju_fishing_core._parse_user_info(utf8_body);
			options.onsuccess && options.onsuccess(user_info)
		}).on("data", function(chunk) {
			gbk_buffers.push(chunk);
		});
	},
};
//用来代理网站进行登录，然后获取这个网站上的用户信息
module.exports = {
	prefix: "/fishing",
	get: {
		//dev.dotnar.com:3000/fishing/init/minyun
		"/init/minyun/:id": function() { //初始化闽运网上售票系统的代理
			var _id = this.params.id;
			var response = this.response;
			response.set("Content-Type", "image/jpeg;charset=UTF-8");
			//验证码图片地址
			minyun_fishing_core.get_img_code(_id, {
				ondata: function(chunk) {
					response.write(chunk);
				},
				onend: function() {
					response.end();
				}
			});
		},
		"/user_info/minyun/:id": function() {
			var _id = this.params.id;
			var self = this;
			minyun_fishing_core.get_user_info(_id, {
				onsuccess: function(user_info) {
					// console.log("USER INFO:", data);
					self.body = ResponObj("json", user_info)
				}
			});
		},
		"/init/mju/:id": function() { //初始化闽运网上售票系统的代理
			var _id = this.params.id;
			var response = this.response;
			response.set("Content-Type", "image/gif;base64");
			//验证码图片地址
			mju_fishing_core.get_img_code(_id, {
				ondata: function(chunk) {
					response.write(chunk);
				},
				onend: function() {
					response.end();
				}
			});
		},
		"/user_info/mju/:id": function() {
			var _id = this.params.id;
			var self = this;
			mju_fishing_core.get_user_info(_id, {
				onsuccess: function(user_info) {
					// console.log("USER INFO:", data);
					self.body = ResponObj("json", user_info)
				}
			});
		},
	},
	post: {
		"/login/minyun/:id": function() {
			var self = this;
			var body = this.request.body;
			var _id = this.params.id;
			minyun_fishing_core.login(_id, {
				username: body.username,
				password: body.password,
				captcha: body.captcha,
				onsuccess: function() {
					self.body = ResponObj("string", "登录成功")
				},
				onerror: function(error_code) {
					self.body = ResponObj("error", error_code)
				}
			});
		},
		"/login/mju/:id": function() {
			var self = this;
			var body = this.request.body;
			var _id = this.params.id;
			mju_fishing_core.login(_id, {
				username: body.username,
				password: body.password,
				captcha: body.captcha,
				onsuccess: function() {
					self.body = ResponObj("string", "登录成功")
				},
				onerror: function(error_code) {
					self.body = ResponObj("error", error_code)
				}
			});
		},
	}
};

/*TEST*/
// var id = "gaubee";
// 	// 获取验证码
// minyun_fishing_core.get_img_code(id, {
// 	onend: function(buffers) {
// 		var res = Buffer.concat(buffers).toString('base64');
// 		console.log("data:image/jpg;base64," + res)
// 	}
// });

// // 输入验证码
// var fs = require("fs");
// setTimeout(function _login() {
// 	var captcha = fs.readFileSync("../_temp/.minyun_img_code.tmp").toString().trim();
// 	if (captcha) {
// 		console.log("成功取到验证码：", captcha);
// 		minyun_fishing_core.login(id, {
// 			username: "gaubee",
// 			password: "gaubee546528",
// 			captcha: captcha,
// 			onsuccess: function() {
// 				console.log("登录成功");
// 				minyun_fishing_core.get_user_info(id, {
// 					onsuccess: function(data) {
// 						console.log("USER INFO:", data);
// 					}
// 				});
// 			},
// 			onerror: function(error_code) {
// 				console.log("ERROR:", error_code);
// 			}
// 		});
// 	} else {
// 		setTimeout(_login, 1000);
// 	}
// }, 1000)

/*TEST MJU*/
// var id = "gaubee"
// mju_fishing_core.get_img_code(id, {
// 	onend: function(buffers) {
// 		var res = Buffer.concat(buffers).toString('base64');
// 		console.log("data:image/gif;base64," + res)
// 	}
// });
// // 输入验证码
// var fs = require("fs");
// setTimeout(function _login() {
// 	var captcha = fs.readFileSync("../_temp/.mju_img_code.tmp").toString().trim();
// 	if (captcha) {
// 		console.log("成功取到验证码：", captcha);
// 		mju_fishing_core.login(id, {
// 			// username: "3111104136",
// 			// password: "gaubee546528",

// 			username: "3111104124",
// 			password: "120473a",

// 			captcha: captcha,
// 			onsuccess: function() {
// 				console.log("登录成功");
// 				mju_fishing_core.get_user_info(id, {
// 					onsuccess: function(data) {
// 						console.log("USER INFO:", data);
// 					}
// 				});
// 			},
// 			onerror: function(error_code) {
// 				console.log("ERROR:", error_code);
// 			}
// 		});
// 	} else {
// 		setTimeout(_login, 1000);
// 	}
// }, 1000)


// var parser = new htmlparser.Parser({
// 	onopentag: function(name, attribs) {
// 		console.log("onopentag:", arguments)
// 	},
// 	ontext: function(text) {
// 		console.log("ontext", text);
// 	},
// 	onclosetag: function(tagname) {
// 		console.log("onclosetag:", arguments)
// 	}
// }, {
// 	decodeEntities: true
// });
// parser.write(`<tr>
// 	<td class="trbg1"><span id="lbxsgrxx_xm">姓名：</span></td>
// 	<td><span id="xm">柯肇丰</span></td>
// 	<td class="trbg1"><span id="lbxsgrxx_pyfx">培养方向：</span></td>
// 	<td colspan="2"><span id="lbl_pyfx"></span></td>
// 	<td class="trbg1" width="183"><span id="lbxsgrxx_sjhm">手机号码：</span></td>
// 	<td width="165"><input name="TELNUMBER" type="text" value="156594445449" id="TELNUMBER"></td>
// </tr>`);
// parser.end();